package com.example.spring_forum.exception;

import com.example.spring_forum.common.AppResult;
import com.example.spring_forum.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j //日志
@ControllerAdvice //控制器通知类
public class GlobalExceptionHandler {
    //body中返回的数据（json形式）
    @ResponseBody
    //异常处理器指定需要处理的异常
    @ExceptionHandler(ApplicationException.class)
    public AppResult handleApplicationException(ApplicationException e){
        //打印异常信息
        e.printStackTrace();
         //打印日志
        log.error(e.getMessage());

        //判断异常信息是否是空
        if(e.getErrorResult()!=null){
            return e.getErrorResult();
        }
        //返回默认异常信息
        return AppResult.failed(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public AppResult handleApplicationHandler(Exception e){

        e.printStackTrace();

        log.error(e.getMessage());

        if(e.getMessage()==null){
            return AppResult.failed(ResultCode.ERROR_SERVICES.getMessage());
        }
        return AppResult.failed(e.getMessage());

    }
}
